package dl.demo.controller;

import dl.demo.entity.User;
import dl.demo.repository.UserRepo;
import dl.demo.tool.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
@CrossOrigin
public class UserCtrl {
    @Autowired
    private UserRepo userRepo;

    @GetMapping("/check")
    public ResponseEntity check(@Param("token") String token){
        int code = JwtUtils.verifyToken(token);
        if(code == 0){
            return Result.data();
        }else{
            return Result.data(401,"请重新登录");
        }
    }

    @PostMapping("/register")
    public ResponseEntity register(@RequestBody User user){
        String username = user.getUsername();
        User u = userRepo.findUserByName(username);
        if(u != null){
            return Result.data(201,"用户已存在");
        }
        userRepo.save(user);
        return Result.data(user);
    }

    @PostMapping("/login")
    public ResponseEntity login(@RequestBody User user){
        String username = user.getUsername();
        String password = user.getPassword();

        User u = userRepo.findUserByName(username);
        System.out.println("login:" + username + " " + password);
        if (u == null) return Result.data(201, "用户不存在");
        if (u.getPassword().equals(password)) {
            Map map = new HashMap();
            map.put("id",u.getId());
            map.put("username",u.getUsername());
            map.put("password",u.getPassword());
            String token = JwtUtils.createToken(map);

            Map frontMap = new HashMap();
            frontMap.put("id",u.getId());
            frontMap.put("username",u.getUsername());
            frontMap.put("token",token);
            return Result.data(token);
        }
        return Result.data(201, "用户名或密码错误");
    }
}
